package cn.circle.system.util;

import java.util.ArrayList;
import java.util.List;

import cn.circle.system.model.SysMenus;
import cn.circle.system.pagemodel.TreeNode;

/**
 * 功能说明：把通过SQL语句获取的数据，通过遍历进行填充
 *
 */
public class TreeUtil {
	private List<SysMenus> lstAll;

	public List<SysMenus> getLstAll() {
		return lstAll;
	}

	public void setLstAll(List<SysMenus> lstAll) {
		this.lstAll = lstAll;
	}
	
    public List<TreeNode> findById(Long parentId)
    {
        List<TreeNode> subs = new ArrayList<TreeNode>();
        for(int i=0;i<lstAll.size();i++)
        {
        	TreeNode mod = recordToTreeNode((SysMenus)lstAll.get(i));
            if(parentId==null)
            {
                if(mod.getPid()==null || mod.getPid() == 0)
                {
                    lstAll.remove(i);
                    i--;
                    List<TreeNode> modSubs = findById(mod.getId());
                    if(modSubs.size()>0)
                    {
                        mod.setChildren(modSubs);
                    }
                    subs.add(mod);
                }
            }
            else
            {
                if(mod.getPid() != null && mod.getPid().longValue() == parentId.longValue())
                {
                    List<TreeNode> modSubs = findById(mod.getId());
                    if(modSubs.size()>0)
                    {
                    	mod.setChildren(modSubs);
                    }
                    subs.add(mod);
                }
            }
        }
        return subs;
    }

    private TreeNode recordToTreeNode(SysMenus record)
    {
    	TreeNode td = new TreeNode();
    	td.setId(Long.valueOf(record.getId()));
    	td.setName(record.getName());
    	td.setIconCls(record.getIconClass());
    	td.setImg(record.getImg());
    	if(record.getParentId() != null)
    		td.setPid(Long.valueOf(record.getParentId()));
    	td.setUrl(record.getUrl());
    	if(record.getType() != null)
    		td.setType(record.getType().shortValue());
    	if(record.getWinId() != null)
    		td.setWinId(record.getWinId());
    	if(record.getWinClass() != null)
    		td.setWinClass(record.getWinClass());
    	if(record.getShortcutIconClass() != null)
    		td.setShortcutIconClass(record.getShortcutIconClass());
    	if(record.getOverImg() != null)
    		td.setOverImg(record.getOverImg());
    	if(record.getShowOrder() != null)
    		td.setShowOrder(record.getShowOrder());
    	if(record.getStatus() != null)
    		td.setStatus(record.getStatus().byteValue());

    	return td;
    }

}
